/**
 * 全站http配置
 *
 * header参数说明
 * serialize是否开启form表单提交
 * isToken是否需要token
 */
import Axios from 'axios'
import store from '@/store/';
import router from '@/router/router'
import { xwwwform } from '@/util/util'
import { getStore } from '@/util/store'
import { baseUrl } from '@/config/env'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import qs from 'qs'

// 不需要验证token的请求
const NoAuthorizations = [
    '/user/getUserInfo',
    '/user/getMenu',
    '/auth/getAccountList'
]

function checkAuthUrl(url) {
    for (let i = 0; i < NoAuthorizations.length; i++) {
        if (NoAuthorizations[i] === url) {
            return true
        }
    }
    return false
}   
// 创建实例时设置配置的默认值
const axios = Axios.create({
    baseURL: baseUrl,
    // 请求超时时间
    timeout: 30000,
    // 跨域请求，允许保存cookie
    withCredentials: true,
    // 开启数组传值解析数组参数，需使用get,params传值
    paramsSerializer: function (params) {
        return qs.stringify(params, { arrayFormat: 'repeat' })
    },
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded;',
        'Access-Control-Allow-Origin': '*'
    }
});
//返回其他状态吗
axios.defaults.validateStatus = function(status) {
    return status >= 200 && status <= 500; // 默认的
};
//跨域请求，允许保存cookie
axios.defaults.withCredentials = true;
// NProgress Configuration
NProgress.configure({
    showSpinner: false
});

//HTTPrequest拦截
axios.interceptors.request.use(config => {

    NProgress.start() // start progress bar
    const needAuth = checkAuthUrl(config.url)
    const sessionId = getStore({name: 'sessionId'})
    // 奇葩的token方式，添加至请求 params 醉了醉了
    if (sessionId && !needAuth) {
        config.params 
            ? config.params.sessionId = sessionId
            : config.params = { sessionId }
    }
    if (config.headers['Content-Type'].indexOf('application/x-www-form-urlencoded') > -1) {
        config.data = xwwwform(config.data)
    } else if (config.headers['Content-Type'].indexOf('application/json') > -1) {
        config.data = JSON.stringify(config.data)
    }
    // headers中配置serialize为true开启序列化
    // if (config.methods === 'post' && config.headers.serialize) {
    //     config.data = serialize(config.data);
    //     delete config.data.serialize;
    // }
    return config
}, error => {
    return Promise.reject(error)
});
//HTTPresponse拦截
axios.interceptors.response.use(res => {
    NProgress.done();
    const status = Number(res.status) || 200;
    const message = res.data.msg || '未知错误';
    const resStatus = Number(res.data.status) || 200

    if (resStatus === 401) store.dispatch('FedLogOut').then(() => router.push({ path: '/login' }));
    if (status !== 200 || resStatus !== 200) {
        return Promise.reject(new Error(message))
    }
    return res;
}, error => {
    console.log(error);
    NProgress.done();
    return Promise.reject(new Error(error));
})

export default axios;
